<style lang="less" scoped>
.main-keyword-group {
    .btn-wrap {
        padding: 5px 0;
    }
    .online,
    .offline {
        margin-left: 0;
    }
    .second-row .manage-templet {
        margin-top: 5px;
    }
    .group {
        display: inline-block;
        vertical-align: top;
    }
}
.row-gap {
    margin-top: 10px;
}
</style>
<template>
    <div class="main main-keyword-group">
        <div class="main-header">
            <el-breadcrumb>
                <el-breadcrumb-item :to="{ path: '/keywords' }">票券申请管理</el-breadcrumb-item>
                <el-breadcrumb-item>票券申请管理</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- <div class="main-menus">
                <el-button type="primary" icon="plus" @click="editItem({}, '新增')">新增票券申请</el-button>
            </div> -->
        </div>
        <div class="main-filters">
            <el-form :inline="true" :model="query">
                <el-form-item>
                    <el-radio-group v-model="query.status">
                        <el-radio-button label="all">全部</el-radio-button>
                        <el-radio-button label="0">未审核</el-radio-button>
                        <el-radio-button label="1">已通过</el-radio-button>
                        <el-radio-button label="2">未通过</el-radio-button>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </div>
        <div class="main-actions">
            <div class="main-actions-label">
                共<em>{{itemsData.pagination.total}}</em>条
            </div>
        </div>
        <el-table
            border
            element-loading-text="Loading..."
            v-loading.body="!itemsData.$resolved"
            :data="itemsData.items"
            @sort-change="onSortItems"
            @selection-change="onSelect"
        >
            <el-table-column sortable="custom" prop="id" label="ID" width="80"></el-table-column>
            <el-table-column label="票券类型" inline-template>
                <div>
                    <p>{{row.parent.name}}-{{row.types.name}}-{{row.type}}</p>
                </div>
            </el-table-column>
            <el-table-column prop="price" label="价格"></el-table-column>
            <!-- <el-table-column label="补价比例" inline-template>
                <p>
                    {{row.b_price ? b_price + '%' : '-'}}
                </p>
            </el-table-column> -->
            <!-- <el-table-column width="150" label="分配票券范围" inline-template>
                <div>
                    <el-tag type="success">{{row.start_no}}</el-tag>
                    <el-tag type="warning">{{row.end_no}}</el-tag>
                </div>
            </el-table-column> -->
            <el-table-column label="客户" inline-template>
                <div>
                    <span> {{row.customer ? row.customer.name : '-'}}</span>
                </div>
            </el-table-column>
            <el-table-column prop="num" label="数量"></el-table-column>
            <el-table-column prop="apply_no" label="申请单号"></el-table-column>
            <el-table-column prop="pay_type" label="支付类型"></el-table-column>
            <el-table-column label="申请时间" inline-template>
                <div>
                    <span> {{row.created_at | date}}</span>
                </div>
            </el-table-column>
            <el-table-column label="审核时间" inline-template>
                <div>
                    <span> {{row.updated_at | date}}</span>
                </div>
            </el-table-column>
            <el-table-column label="申请人" inline-template>
                <div>
                    <span> {{row.creator ? row.creator.name : '-'}}</span>
                </div>
            </el-table-column>
            <el-table-column label="审核人" inline-template>
                <div>
                    <span> {{row.leader ? row.leader.name : '-'}}</span>
                </div>
            </el-table-column>
            <el-table-column prop="status" label="状态" inline-template>
               <div>
                    <el-tag type="success" v-if="row.status === 1">已通过</el-tag>
                    <el-tag type="grey" v-if="row.status === 0">待审核</el-tag>
                    <el-tag type="grey" v-if="row.status === 2">未通过</el-tag>
               </div>
            </el-table-column>
            <el-table-column label="操作" inline-template v-if="user.role.name.indexOf('管理员') > -1">
                <div class="item-menus">
                    <el-button size="small" v-if="+row.status === 0" type="primary" @click="editItem(row, '编辑')">审核通过</el-button>
                     <router-link v-if="+row.status === 1" :to="'/tickets/' + row.id"><el-button size="small">票券分配</el-button></router-link>
                    <el-button size="small" v-if="+row.status === 0" type="warning" @click="deleteItem(row)">取消审核</el-button>
                    <el-button size="small" v-if="+row.status === 1 && row.type === '备售'" type="success" @click="active(row)">激活票券</el-button>
                    <!-- <el-button size="small" type="danger" v-if="row.keywords.length < 1" @click="deleteItem(row)">删除</el-button> -->
                </div>
            </el-table-column>
        </el-table>

        <el-pagination
            v-if="itemsData.$resolved"
            layout="prev, pager, next, jumper"
            :total="itemsData.pagination.total"
            :current-page="query.page_num"
            :page-size="query.page_size"
            @current-change="onPageChange"
        >
        </el-pagination>

        <el-dialog
            title="审核通过"
            :visible.sync="editDialogVisible"
            width="50%"
        >
            <el-form :model="editData">
                <el-form-item label="票券类型">
                    <el-input :disabled="true" v-model="tickeName" style="width: 30%;"></el-input>
                </el-form-item>
                <el-form-item label="申请单编号">
                    <el-input v-model="editData.apply_no" placeholder="输入申请单编号" style="width: 30%;"></el-input>
                </el-form-item>
                <!-- <el-form-item v-for="attr in attrs" v-bind:key="attr.id" :label="attr.name">
                    <el-checkbox-group v-model="attr.values" @change="onAttrChange(attr)">
                        <el-checkbox v-for="item in attr.items" v-bind:key="item.id" :label="item">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="节假日">
                    <el-checkbox-group v-model="editData.dates">
                        <el-checkbox v-for="item in dates" v-bind:key="item.id" :label="item">{{item.name}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item> -->
                <el-form-item label="有效开始时间">
                    <DatePicker type="date" v-model="editData.start_time" format="yyyy-MM-dd"></DatePicker>
                    <span class="tips" style="margin-left:.6em;color:#999">* 票券可使用开始时间</span>
                </el-form-item>
                <el-form-item label="有效截止时间">
                    <DatePicker type="date" v-model="editData.end_time" format="yyyy-MM-dd"></DatePicker>
                    <span class="tips" style="margin-left:.6em;color:#999">* 票券可使用截止时间</span>
                </el-form-item>
                <!-- <el-form-item label="出票后生效时长（天）" v-if="tickeName.indexOf('备售')">
                    <el-input-number v-model="editData.days" style="width: 30%;"></el-input-number>
                    <span class="tips" style="margin-left:.6em;color:#999">* 出票后开始计算</span>
                </el-form-item> -->
                <el-form-item label="申请人">
                    <el-input :disabled="true" v-model="editData.creator.name" placeholder="输入申请单编号" style="width: 30%;"></el-input>
                </el-form-item>
                <el-form-item label="申请价格">
                    <el-input v-model="editData.price" style="width: 30%;"></el-input>
                </el-form-item>
                <el-form-item label="补价">
                    <el-input v-model="editData.b_percent" placeholder="补价比例" style="width: 20%;"></el-input>
                    <span class="tips" style="margin-left:.6em;color:#999">* 在非可用时间使用补差价</span>
                </el-form-item>
                <el-form-item label="付款方式">
                    <el-select v-model="editData.pay_type">
                    <el-option
                        v-for="item in payTypes"
                        :label="item"
                        :value="item"
                        :key="item"
                    ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input v-model="editData.remark" type="textarea" placeholder="备注" style="width: 30%;"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitEdit">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import ListController from '../controllers/list';

import ApplyModel from '../models/apply';
import TicketModel from '../models/ticket';
import RoleModel from '../models/role';
import AttributeModel from '../models/attribute';
import DateModel from '../models/special-date';

import Promise from 'bluebird';

export default new ListController({
    components: {
        DatePicker: require('../components/date-picker')
    },
    data() {
        return {
            ListModel: ApplyModel,

            query: {
                page_num: 1,
                page_size: 20,
                sort: '',
                status: 'all',
            },

            user: TTXS.user,
            attrs: [],
            dates: [],

            payTypes: ['现金', '转账', '刷卡', '微信', '支付宝', '微信', '串换', '挂账', '免单'],
            editData: {
                creator: {},
                end_time: new Date(),
                start_time: new Date(),
                price: 0,
                dates: [],
            },
            tickeName: '',
            editDialogVisible: false
        };
    },
    methods: {
        beforeLoadItems() {
            return Promise.all([
                this.loadAttrs(),
                this.loadDates()
            ])
        },
        debugItem(row) {
            this.$confirm('确认调试该项？')
            .then(() => {
                this.ListModel.update({
                    id: row.id,
                    status: 1
                }).$promise;
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        pushItem(row) {
            this.$confirm('确认上线该项？')
            .then(() => {
                return this.ListModel.update({
                    id: row.id,
                    status: 1
                }).$promise
                .then(() => {
                    this.loadItems();
                });
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        deleteItem(row) {
            this.$confirm('确认取消该票券申请？')
            .then(() => {
                return this.ListModel.delete({
                    id: row.id
                }).$promise;
            })
            .then(() => {
                return this.loadItems();
            })
            .catch(err => {
                throw new Error(err);
            });
        },
        editItem(row) {
            const lastyear = new Date();
            lastyear.setFullYear(lastyear.getFullYear() + 1);
            this.tickeName = row.parent.name + '-' + row.types.name + '-' + row.type;
            this.editData = Object.assign({
                creator: {},
                end_time: new Date(),
                days: 30,
                start_time: '',
                price: 0,
                dates: [],
                b_percent: 0,
                pay_type: ''
            }, row);

             this.editData.end_time = lastyear;
            this.editDialogVisible = true;
        },
        submitEdit() {
            let params = null;
            let $submitPromise = null;

            if(!this.editData.end_time) {
                this.$message.info('请设置到期时间');
                return;
            }

            if(!/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(this.editData.price)) {
                this.$message.info('请输入正确的价格');
                return;
            }

            if(!this.editData.apply_no) {
                this.$message.info('请输入申请单号');
                return;
            }

            if(!this.editData.apply_no) {
                this.$message.info('请输入申请单号');
                return;
            }

            if(this.editData.id > 0) {
                $submitPromise = this.ListModel.update(this.editData).$promise;
            }
            else {
                params = Object.assign({}, this.editData);
                $submitPromise = this.ListModel.save(params).$promise;
            }

            $submitPromise
            .then(res => {
                if(res.code && res.code !== 200) {
                    this.$message.error(res.message);
                    return;
                }
                this.editDialogVisible = false;
                this.$message({
                    message: '提交成功！',
                    type: 'success'
                });
                this.loadItems();
            })
            .catch(err => {
                this.$message.error(err);
            });
        },
        loadAttrs() {
            const attrs = [
                // { type: 'role', key: 'roles', name: '场景' },
                { type: 'weekdays', key: 'weekdays', name: '使用限制' },
            ];

            return AttributeModel.get()
            .$promise
            .then(attrsMap => {
                return attrs.map(attr => {
                    attr.items = attrsMap[attr.type] || [];
                    attr.values = [];

                    return attr;
                });
            })
            .tap(attrs => {
                this.attrs = attrs;
            });
        },
        loadDates() {
            return DateModel.query({})
            .$promise
            .then(dates => {
                this.dates = dates.items;
            })
        },
        onAttrChange(attr) {
            this.editData[attr.key] = attr.values.reduce((val, item) => {
                return val | item.id;
            }, 0);
        },
        active(row) {
            this.$confirm('确认激活该票券申请下的票券？')
            .then(() => {
                return this.ListModel.update({
                    id: 0,
                    status: TicketModel.UNUSED,
                    apply_id: row.id,
                }).$promise
                .then(() => {
                    this.loadItems();
                });
            });
        }
    }
});
</script>
